package com.example.springbootmqdemo.aajuc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Classname: Thread1
 *
 * @Author: Jam
 * @Create 2022/12/2 - 18:34
 * @Version 1.0   Lock版的生产者 消费者模式
 */
public class Thread4 {
    public static void main(String[] args) {
        Ticketkk ticket3  = new Ticketkk();

        //lambda表达式 (参数)->{代码}
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                try {
                    ticket3.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                try {
                    ticket3.decry();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}
//1. new  ReentrantLock()  Condition 监视
//2. lock.lock();//加锁
//3.  try/catch  finally 块
   //3.1 判断 while(){  等待  }
   //3.2 业务 逻辑代码
   //3.1 通知  signalAll、notifyAll
//4.  lock.unlock();//解锁

class Ticketkk{ //资源类
    //属性 方法
    private  int number = 0;

    Lock lock = new ReentrantLock();
    Condition  Condition = lock.newCondition(); //取代wai notifyAll 方法
    //+1
    public  void incr() throws InterruptedException {

        lock.lock();//1.加锁

        try {
            //2.业务代码start
            while (number != 0){
                //等待
                Condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"---"+number);
            number++;
            //通知其他线程 我+1完毕
            Condition.signalAll();
            //业务代码end
        } catch (Exception e) {
            e.getStackTrace();
        }finally {
            lock.unlock();//3.解锁
        }
    }

    //-1
    public  void decry() throws InterruptedException{

        lock.lock();//1.加锁

        try {
            //2.业务代码start
            while (number == 0){
                //等待
                Condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"---"+number);
            number--;
            //通知其他线程 我-1完毕
            Condition.signalAll();
            //业务代码end
        } catch (Exception e) {
            e.getStackTrace();
        }finally {
            lock.unlock();//3.解锁
        }


    }
}